package batch_jobs;


require Exporter;


our @ISA = qw(Exporter);
our $VERSION = 1.00;
our @EXPORT = qw(	batch_gene_pairs
					fill_table__batch_gene_pairs
					fill_table__batch_jobs
					);

use strict;
use warnings;

# function declarations
#_________________________________________________________________________________________

#     fill_batch_gene_pairs table

#        fill table with gene pairs

#_________________________________________________________________________________________
sub	fill_table__batch_jobs($$$)
{
	my ($dbh, $cnt_batches, $job_description)  = @_;
	print STDERR "Preparing batch table...\n";
	$dbh->{PrintError} = 1;
	$dbh->do("DELETE FROM batch_jobs where category = '$job_description';");
	$dbh->do("COPY batch_jobs(batch, category) from STDIN;");
	for my $batch( 0 .. $cnt_batches - 1)
	{
		print STDERR ".";
		$dbh->func("$batch\t$job_description\n", 'putline');
	}
	$dbh->func("\\.\n", 'putline');
	$dbh->func('endcopy');
	print STDERR "Done\n";
}


#_________________________________________________________________________________________

#     fill_batch_gene_pairs table

#        fill table with gene pairs

#_________________________________________________________________________________________
sub fill_table__batch_gene_pairs($\@$$)
{
	
	my ($dbh, $gene_pairs, $job_description, $batch_size) = @_;
	$dbh->{PrintError} = 1;
	$dbh->do("DELETE FROM batch_gene_pairs where category = '$job_description';");
	$dbh->do("COPY batch_gene_pairs(batch, gene_id1, gene_id2, category) from STDIN;");
	print STDERR scalar @$gene_pairs, " gene pairs\n";
	my $cnt_blast	= 0;
	my $batch		= 0;
	for my $gene_pair(@$gene_pairs)
	{
		++$batch if (++$cnt_blast % $batch_size == 0);
				
				
		$dbh->func("$batch\t$gene_pair->[0]\t$gene_pair->[1]\t$job_description\n",
								'putline');
	}
	$dbh->func("\\.\n", 'putline');
	$dbh->func('endcopy');
	return $batch + 1;
	
}


#_________________________________________________________________________________________

#     fill_batch_gene_pairs table

#        wrapper around everything

#_________________________________________________________________________________________
sub batch_gene_pairs($\@$)
{
	my ($dbh, $gene_pairs, $job_description) = @_;
	my $batch_cnt = fill_table__batch_gene_pairs($dbh, @$gene_pairs, $job_description);
	fill_table__batch_jobs($dbh, $batch_cnt, $job_description);
}






1;

